<template>
  <div class="app-container">
    <el-card class="search-container">
      <el-form :inline="true" :model="ProductSkuForm" class="search-form">
        <el-form-item label="库存编码">
          <el-input
            v-model="ProductSkuForm.skuCode"
            size="small"
            placeholder="请输入库存编码"
            clearable
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="商品价格">
          <el-input
            v-model="ProductSkuForm.minPrice"
            size="small"
            placeholder="最低价"
            style="width: 100px"
          />
          <span class="price-separator">-</span>
          <el-input
            v-model="ProductSkuForm.maxPrice"
            size="small"
            placeholder="最高价"
            style="width: 100px"
          />
        </el-form-item>

        <el-form-item label="库存状态">
          <el-select
            v-model="ProductSkuForm.stockStatus"
            size="small"
            placeholder="请选择"
            style="width: 120px"
            clearable
          >
            <el-option label="全部" value=""/>
            <el-option label="紧张(<10)" value="low"/>
            <el-option label="一般(10-30)" value="medium"/>
            <el-option label="充足(30-60)" value="high"/>
            <el-option label="富余(≥60)" value="abundant"/>
          </el-select>
        </el-form-item>

        <el-form-item label="商品详情">
          <el-input
            v-model="ProductSkuForm.detailKeyword"
            size="small"
            placeholder="输入关键词"
            style="width: 180px"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleSearch"
          >查询
          </el-button>
          <el-button
            size="small"
            icon="el-icon-refresh"
            @click="resetSearch"
          >重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table
      :data="tableData"
      stripe
      max-height="800"
      class="full-height"
      @selection-change="handleSelectionChange"
      style="width: 100%;"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="skuCode" label="库存编码"></el-table-column>
      <el-table-column prop="price" label="商品价格"></el-table-column>
      <el-table-column prop="stock" label="库存数量">
        <template #default="{row}">
          <el-progress
            :percentage="getStockPercentage(row.stock)"
            :color="getStockColor(row.stock)"
            :format="formatStockText"
            :stroke-width="17"
            :text-inside="true"
          />
        </template>
      </el-table-column>
      <el-table-column prop="attributes" label="商品详情">
        <template #default="{row}">
          <div class="product-attributes" v-if="row.attributes">
            <div v-for="(value, key) in safeJsonParse(row.attributes)" :key="key" class="attribute-item">
              <span class="attribute-key">{{ key }}：</span>
              <span class="attribute-value">{{ value }}</span>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="商品创建时间"></el-table-column>

      <el-table-column label="操作">
        <template #default="{row}">
          <el-button
            size="mini"
            @click="openDialog(row)"
            icon="el-icon-edit"
          >编辑
          </el-button>

          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        :page-sizes="[3, 6, 9]"
        @current-change="handleCurrentChange"
        :current-page="ProductSku.pageNum"
        :page-size="ProductSku.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
      <el-button style="margin-left: 10px" size="small" type="primary" plain @click="toPage">
        跳转
      </el-button>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="goodsForm"
        :model="ProductSku"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="ProductSku.productId"></el-input>
        </el-form-item>
        <el-form-item label="库存编码" prop="skuCode">
          <el-input v-model="ProductSku.skuCode"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model.number="ProductSku.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model.number="ProductSku.stock" type="number"></el-input>
        </el-form-item>

        <el-form-item label="商品详情">
          <div v-for="(value, key, index) in parsedAttributes" :key="index" class="detail-item">
            <el-input
              v-model="editableKeys[index]"
              placeholder="属性名"
              style="width: 30%"
              @change="handleKeyChange(index, key)"
            />
            <el-input
              v-model="editableValues[key]"
              placeholder="属性值"
              style="width: 30%; margin-left: 5px"
              @input="handleValueChange(key, $event)"
            />
            <el-button
              @click="removeAttribute(key)"
              icon="el-icon-delete"
              type="danger"
              style="margin-left: 5px"
            />
          </div>
          <el-button @click="addAttribute" icon="el-icon-plus" type="primary">
            添加属性
          </el-button>
        </el-form-item>
        <el-form-item label="商品创建时间" prop="createdAt">
          <el-date-picker
            v-model="ProductSku.createdAt"
            type="datetime"
            placeholder="请选择创建时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveGoods">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { protSku, resetSearch, deleteProduct, modifyGoods } from '@/api/product/productSku'

export default {
  name: 'StockMgr',
  data() {
    return {
      title: '',//弹窗名字
      dialogVisible: false,//弹窗开关
      editableValues: {}, // 添加这行
      editableKeys: [],//属性名数组
      tableData: [],//后端返回的数据
      selectedRows: [],//获取查询行中信息
      ProductSku: {//发送给后端的数据
        id: 0,//库存id
        productId: 0,//商品id
        attributes: {},//商品详情
        price: null,//库存价格
        stock: null,//库存数量
        createdAt: null,//商品创建时间
        pageSize: 3,//分页参数
        pageNum: 1,//分页参数
        skuCode: '',//商品编号
        minPrice: null,//模糊查询最低价格
        maxPrice: null,//模糊查询最高价格
        stockStatus: null,//模糊查询状态
        detailKeyword: ''//商品详情模糊查询
      },
      // ✅ 专门用于表单绑定的商品信息
      ProductSkuForm: {
        id: 0,//库存编号
        productId: 0,//商品id
        attributes: {},//商品详情
        price: null,//商品价格
        stock: null,//库存数量
        createdAt: null,//创建时间//时间
        skuCode: '',//商品编号
        pageSize: 3,//分页参数
        pageNum: 1,//分页参数
      },
      total: 0,
      rules: {

        skuCode: [
          { required: true, message: '请输入库存编码', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格' },
          { type: 'number', message: '必须为数字' },
          { validator: v => v >= 0, message: '不能为负数' }
        ],
        stock: [
          { required: true, message: '请输入库存数量' },
          { type: 'number', message: '必须为数字' },
          { validator: v => v >= 0, message: '不能为负数' }
        ]
      }
    }
  },
  computed: {

    parsedAttributes: {//商品详情
      get() {
        // 优先使用 editableValues
        if (this.editableValues && Object.keys(this.editableValues).length > 0) {
          return this.editableValues
        }

        // 否则解析 ProductSku.attributes
        if (!this.ProductSku.attributes) return {}

        try {
          return typeof this.ProductSku.attributes === 'string'
            ? JSON.parse(this.ProductSku.attributes)
            : this.ProductSku.attributes
        } catch (e) {
          console.error('JSON解析失败:', e)
          return {}
        }
      },
      set(value) {
        this.editableValues = value
        this.editableKeys = Object.keys(value)
        this.ProductSku.attributes = JSON.stringify(value)
      }
    }
  },
  created() {
    this.protSku()
  },
  methods: {

    handleValueChange(key, value) {
      this.editableValues = {
        ...this.editableValues,
        [key]: value
      };
      // 同步到表单数据
      this.ProductSku.attributes = JSON.stringify(this.editableValues);
    },

    handleKeyChange(index, oldKey) {
      const newKey = this.editableKeys[index].trim()
      if (!newKey) {
        this.$message.warning('属性名不能为空')
        return
      }

      if (this.editableKeys.filter(k => k === newKey).length > 1) {
        this.$message.warning('属性名不能重复')
        return
      }
      // const newKey = this.editableKeys[index].trim();
      // if (!newKey) return;

      const newValues = {...this.editableValues};
      newValues[newKey] = newValues[oldKey];
      delete newValues[oldKey];

      this.editableValues = newValues;
      this.editableKeys[index] = newKey;
      this.ProductSku.attributes = JSON.stringify(newValues);
    },
    safeJsonParse(jsonStr) {
      try {
        return jsonStr ? JSON.parse(jsonStr) : {}
      } catch (e) {
        console.error('JSON解析错误:', e)
        return {}
      }
    },


    addAttribute() {
      const baseName = '属性'
      let newKey = baseName
      let counter = 1

      // 确保 editableKeys 存在
      if (!Array.isArray(this.editableKeys)) {
        this.editableKeys = []
      }

      // 生成唯一键名
      while (this.editableKeys.includes(newKey)) {
        newKey = `${baseName}${counter++}`
      }

      // 更新 editableValues
      this.editableValues = {
        ...this.editableValues,
        [newKey]: '默认值'
      }

      // 更新 editableKeys
      this.editableKeys = [...this.editableKeys, newKey]

      // 同步到表单数据
      this.ProductSku.attributes = JSON.stringify(this.editableValues)
    },
    removeAttribute(key) {
      this.$confirm('确定删除此属性吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 使用 Vue.set 或直接替换对象
        const newAttributes = { ...this.parsedAttributes }
        delete newAttributes[key]
        this.parsedAttributes = newAttributes // 直接替换整个对象

        // 更新 editableKeys
        this.editableKeys = this.editableKeys.filter(k => k !== key)

        // 如果需要同步到 editableValues，也更新它
        if (this.editableValues) {
          const newValues = { ...this.editableValues }
          delete newValues[key]
          this.editableValues = newValues
        }
      }).catch(() => {
        // 用户点击取消
      })
    },
    openDialog(row) {
      this.dialogVisible = true
      const { pageSize, pageNum } = this.ProductSku

      if (row) {
        this.title = '编辑商品'
        const rowData = JSON.parse(JSON.stringify(row))

        this.ProductSku = {
          ...this.ProductSku,
          ...rowData,
          pageSize,
          pageNum
        }

        // 初始化属性编辑器
        try {
          this.editableValues = typeof rowData.attributes === 'string'
            ? JSON.parse(rowData.attributes)
            : rowData.attributes || {}
          this.editableKeys = Object.keys(this.editableValues)
        } catch (e) {
          console.error('属性解析失败:', e)
          this.editableValues = {}
          this.editableKeys = []
        }
      } else {
        this.title = '新增商品'
        this.ProductSku = {
          ...this.ProductSku,
          id: 0,
          skuCode: '',
          price: null,
          stock: null,
          attributes: '{}' // 确保初始化为空JSON对象字符串
        }
        this.editableValues = {}
        this.editableKeys = []
      }
    },



    // 修改后的 saveGoods 方法
    saveGoods() {
      const loading = this.$loading({ lock: true, text: '正在保存...' });
      const submitData = {
        ...this.ProductSku,
        attributes: JSON.stringify(this.editableValues),
        createdAt: this.ProductSku.createdAt || new Date().toISOString()
      };

      // 直接使用modifyGoods API
      modifyGoods(submitData)
        .then(res => {
          this.$message.success('修改成功');
          this.dialogVisible = false;
          this.protSku();
          this.ProductSku.createdAt = null;
        })
        .catch(error => {
          const msg = error.response?.data?.message || '操作失败';
          this.$message.error(`修改失败: ${msg}`);
        })
        .finally(() => loading.close());
    },
    handleDelete(row) {
      this.$confirm('确认删除该商品吗?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteProduct(row.id).then(() => {

          this.$message.success('删除成功')
          this.protSku()
          this.ProductSku.createdAt = null;

        })
      })
    },
    // 添加库存方法
    // 修改后的 addSku 方法

    handleSearch() {
      resetSearch(this.ProductSkuForm).then(ret => {
        this.tableData = ret.data.list
        this.total = ret.data.total

      })
    },
    resetSearch() {
      // 正确重置搜索表单绑定的数据对象
      this.ProductSkuForm = {
        ...this.ProductSkuForm,  // 保留分页参数
        skuCode: '',
        minPrice: null,
        maxPrice: null,
        stockStatus: '',
        detailKeyword: ''
      }

      // 同时重置实际查询参数（根据接口需要）
      this.ProductSku = {
        ...this.ProductSku,
        skuCode: '',
        minPrice: null,
        maxPrice: null,
        stockStatus: '',
        detailKeyword: ''
      }

      // 立即执行新的查询
      this.handleSearch()
    },
    getStockPercentage(stock) {
      return Math.min(100, stock || 0)
    },
    getStockColor(stock) {
      if (stock < 10) return '#F56C6C'
      if (stock < 30) return '#E6A23C'
      if (stock < 60) return '#67C23A'
      return '#409EFF'
    },
    formatStockText(percentage) {
      const stock = Math.round((percentage / 100) * 100)
      if (stock < 10) return `${stock} (紧张)`
      if (stock < 30) return `${stock} (一般)`
      if (stock < 60) return `${stock} (充足)`
      return `${stock} (富余)`
    },
    protSku() {//查询全部

      protSku(this.ProductSku).then(ret => {
        this.tableData = ret.data.list
        this.total = ret.data.total

      })
    },
    handleSizeChange(val) {
      this.ProductSku.pageSize = val
      this.protSku()
    },
    handleCurrentChange(val) {
      this.ProductSku.pageNum = val
      this.protSku()
    },
    handleSelectionChange(val) {//获取行中的信息
      this.selectedRows = val
    },
    toPage() {
      this.protSku()
    }
  }
}
</script>

<style>
/* 内容容器样式 */
.app-container {
  padding-bottom: 60px; /* 等于或略大于分页栏高度 */
  height: calc(100vh - 60px); /* 可选：固定高度计算 */
  overflow-y: auto; /* 允许内容滚动 */
}

/* 分页栏样式保持你的原有代码 */
.pagination-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}



.full-height {
  display: flex;
  flex-direction: column;
  height: auto;
}

.product-attributes {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.attribute-item {
  display: flex;
  align-items: center;
}

.attribute-key {
  font-weight: 500;
  color: #606266;
  min-width: 60px;
}

.attribute-value {
  color: #409EFF;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.search-container {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.el-form-item {
  margin-bottom: 10px;
  margin-right: 15px;
}

.price-separator {
  margin: 0 5px;
  color: #999;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.detail-item .el-input {
  margin-right: 8px;
}
</style>
